import { contextBridge, ipcRenderer } from 'electron'
import { electronAPI } from '@electron-toolkit/preload'
import loadWasm from '../../resources/wasm/cpp_mod.wasm?loader'

// Custom APIs for renderer
const api = {
  // 将minimize方法传给vue，ipcRenderer.send是向主进程发消息的(用ipcRenderer.on('xxx')从主进程接收消息)
  // vue调用window.electronAPI.minimize()会向主进程发送消息
  /**
   * 窗口最小化
   */
  minimize() {
    ipcRenderer.send('window-minimize')
  },
  /**
   * 窗口最大化
   */
  maximize() {
    ipcRenderer.send('window-maximize')
  },
  /**
   * 关闭窗口
   */
  close() {
    ipcRenderer.send('window-close')
  },
  /**
   * 集成c++ module
   * @param {string} mod 方法名
   */
  module(mod) {
    return new Promise((resolve, reject) => {
      loadWasm()
        .then(instance => {
          // console.log('instance: ', instance);
          if (typeof instance.exports[mod] === 'function') {
            resolve(instance.exports[mod]);
          } else {
            reject(new Error(`Module "${mod}" is not a function`));
          }
        })
        .catch(reject);
    })
  },
  /**
   * 接收主进程消息 根据窗口尺寸变化，修改svg画布倍率
   */
  getResize(cb) {
    ipcRenderer.on('window-size', (_, resize) => cb(resize))
  }
}

// Use `contextBridge` APIs to expose Electron APIs to
// renderer only if context isolation is enabled, otherwise
// just add to the DOM global.
// console.log('版本：', process.versions)
if (process.contextIsolated) {
  try {
    contextBridge.exposeInMainWorld('electron', electronAPI)
    contextBridge.exposeInMainWorld('api', api)
  } catch (error) {
    console.error(error)
  }
} else {
  window.electron = electronAPI
  window.api = api
}
